package com.employee.attendance_daka.service.Impl;

import com.employee.attendance_daka.domain.Attendance;
import com.employee.attendance_daka.mapper.AttendanceMapper;
import com.employee.attendance_daka.service.AttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Service
public class AttendanceServiceImpl implements AttendanceService {

    @Autowired
    private AttendanceMapper attendanceMapper;

    /**
     * 添加考勤记录
     * @param employeeId 员工ID
     * @param employeeName 员工姓名
     * @param clockTime 打卡时间
     * @param status 打卡状态（0-未迟到，1-迟到）
     * @param remark 备注
     * @return 添加结果
     */
    @Override
    @Transactional
    public String addAttendance(String employeeId, String employeeName, LocalDateTime clockTime, String status, String remark) {
        // 参数校验
        if (employeeId == null || employeeId.trim().isEmpty()) {
            return "员工ID不能为空";
        }
        if (employeeName == null || employeeName.trim().isEmpty()) {
            return "员工姓名不能为空";
        }
        if(!attendanceMapper.isEmployee(employeeId)){
            return "该员工不是公司员工";
        }
        if(!attendanceMapper.isEmployeeMatch(employeeId,employeeName)){
            return "员工ID与员工姓名不匹配";
        }
        try {
            // 1. 判断该员工是否为公司员工
            if (!attendanceMapper.isEmployee(employeeId)) {
                return "该员工不是公司员工";
            }
            //获取当前打卡时间
            LocalDateTime actualClockTime = LocalDateTime.now();
            // 2. 判断员工打卡时间是否迟到（9点为界限）
            String attendanceStatus;
            LocalTime clockInTime = actualClockTime.toLocalTime();
            LocalTime lateThreshold = LocalTime.of(9, 0); // 9:00

            if (clockInTime.isAfter(lateThreshold)) {
                attendanceStatus = "1"; // 迟到
            } else {
                attendanceStatus = "0"; // 未迟到
            }

            // 添加考勤记录
            int result = attendanceMapper.addAttendance(employeeId, employeeName, clockTime, attendanceStatus, remark);
            if (result > 0) {
                if ("1".equals(attendanceStatus)) {
                    return "打卡成功，但已迟到";
                } else {
                    return "打卡成功，未迟到";
                }
            } else {
                return "打卡失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "系统异常，请稍后重试";
        }
    }
    /**
     * 删除考勤记录
     * @param id 考勤记录ID
     * @return 删除结果
     */
    @Override
    @Transactional
    public String deleteAttendance(int id) {
        try{
            //1.判断是否有该打卡记录
           Attendance attendance = attendanceMapper.getAttendanceById(id);//获取打卡记录
           if (attendance == null) {
               return "没有该打卡记录";
           }
            //判断删除的是否为当天的打卡记录，如果是，则返回只能删除历史打卡记录，如果不是，则删除
            LocalDateTime now = LocalDateTime.now();
            if (attendance.getClockTime().toLocalDate().equals(now.toLocalDate())) {
                return "只能删除历史打卡记录,当天记录不能删除";
            }
            // 删除考勤记录
            int result = attendanceMapper.deleteAttendance(id);
            if (result > 0) {
                return "删除成功";
            } else {
                return "删除失败";
            }
        }catch (Exception e){
            e.printStackTrace();
            return "系统异常，请稍后重试";
        }
    }
    /**
     * 更新考勤记录
     * @param id 考勤记录ID
     * @param remark 备注
     * @return 更新结果
     */

    @Override
    @Transactional
    public String updateAttendance(int id, String remark){
        try{
            // 参数校验
            if (remark == null) {
                remark = "";
            }//检查传入的 remark 参数是否为 null如果 remark 为 null，则将其设置为空字符串 ""这是为了防止在后续处理中出现空指针异常（NullPointerException）
            
            // 检查是否有该打卡记录
            Attendance attendance = attendanceMapper.getAttendanceById(id);
            if (attendance == null) {
                return "没有该打卡记录";
            }
            
            // 更新考勤记录
            int result = attendanceMapper.updateAttendance(id, remark);
            if(result > 0){
                return "更新成功";
            }else {
                return "更新失败";
            }
        }catch (Exception e)
            {
            e.printStackTrace();
            return "系统异常，请稍后重试";
        }
    }
    
    /**
     * 获取打卡记录
     * @param employeeId 员工ID
     * @param employeeName 员工姓名
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 打卡记录列表
     */
    @Override
    public List<Attendance> getAttendance(String employeeId, String employeeName, LocalDateTime startTime, LocalDateTime endTime) {
        return attendanceMapper.getAttendancesByCondition(employeeId, employeeName, startTime, endTime);
    }
}